package com.dgut.springsecurity.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class AdminLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    private static final Logger log = LoggerFactory.getLogger(UserLoginSuccessHandler.class);

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {


        // 会帮我们跳转到上一次请求的页面上
        //super.onAuthenticationSuccess(request, response, authentication);
        System.out.println(request.getParameter("adjust"));
        if(request.getParameter("adjust")==null) {
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            String sessionId = request.getSession().getId();
            PrintWriter writer = response.getWriter();
            writer.write(sessionId);
            writer.flush();
            writer.close();
        }
        else{
            System.out.println(authentication);
            RequestDispatcher rd=request.getRequestDispatcher("browser");
            rd.forward(request,response);
            //response.sendRedirect("browser/admin");
        }
    }

}
